import axios from 'axios';
import { ElMessage } from 'element-plus';

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080', // 使用环境变量或默认值
  timeout: 60000, // 设置超时时间为60秒
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    console.log('Full request URL:', `${config.baseURL}${config.url}`);
    console.log('Request method:', config.method);
    console.log('Request headers:', config.headers);
    console.log('Request data:', config.data);
    
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    console.log('Response status:', response.status);
    console.log('Response headers:', response.headers);
    console.log('Response data:', response.data);
    return response.data;
  },
  error => {
    console.error('Error details:', {
      message: error.message,
      code: error.code,
      config: error.config,
      response: error.response
    });
    
    if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接');
      return Promise.reject(error);
    }
    
    const { response } = error;
    
    if (response && response.status) {
      const errorMessage = response.data?.message || '请求失败';
      
      switch (response.status) {
        case 400:
          ElMessage.error(`请求错误: ${errorMessage}`);
          break;
        case 401:
          ElMessage.error('未授权，请重新登录');
          // 可以在这里处理登出操作
          break;
        case 403:
          ElMessage.error('拒绝访问');
          break;
        case 404:
          ElMessage.error(`请求的资源不存在: ${errorMessage}`);
          break;
        case 500:
          ElMessage.error(`服务器错误: ${errorMessage}`);
          break;
        default:
          ElMessage.error(`连接错误: ${errorMessage}`);
      }
    } else {
      ElMessage.error('网络异常，请检查您的网络连接');
    }
    
    return Promise.reject(error);
  }
);

// 封装GET请求
export function get(url, params) {
  return service({
    url,
    method: 'get',
    params
  });
}

// 封装POST请求
export function post(url, data) {
  return service({
    url,
    method: 'post',
    data
  });
}

// 封装PUT请求
export function put(url, data) {
  return service({
    url,
    method: 'put',
    data
  });
}

// 封装DELETE请求
export function del(url, params) {
  return service({
    url,
    method: 'delete',
    params
  });
}

export default service; 